﻿Imports System
Imports System.IO
Imports BKO.Domain.Model
Imports BKO.Domain.Services
Imports BKO.Services
Imports BKO.UIControls

Public Class frmLogin
	Private sLoad As Boolean
	Private userService As ITUserService

	Private Sub frmLogin_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
		PrPath = Directory.GetParent(Application.ExecutablePath).ToString & "\"
		txtPassword.Focus()
		txtPassword.SelectAll()
		txtPassword.Focus()
	End Sub

	Private Sub Find_LANG()
		cmbLang.Items.Clear()

		Try
			' Only get files that begin with the letter "c."
			Dim dirs As String() = Directory.GetFiles(PrPath & "lang\", "*.ini")
			' Console.WriteLine("The number of files starting with c is {0}.", dirs.Length)
			Dim dir As String

			For Each dir In dirs
				Dim d() As String
				d = Split(dir, "\")

				cmbLang.Items.Add(d(d.Length - 1))
			Next
		Catch e1 As Exception
			'Console.WriteLine("The process failed: {0}", e1.ToString())
		End Try
	End Sub

	Private Sub Find_DB()
		cmbBD.Items.Clear()

		Try
			' Only get files that begin with the letter "c."
			Dim dirs As String() = Directory.GetFiles(BasePath, "*.mdb")
			' Console.WriteLine("The number of files starting with c is {0}.", dirs.Length)
			Dim dir As String

			For Each dir In dirs
				Dim d() As String
				d = Split(dir, "\")

				cmbBD.Items.Add(d(d.Length - 1))
			Next
		Catch e1 As Exception
			'Console.WriteLine("The process failed: {0}", e1.ToString())
		End Try
	End Sub

	Private Sub User_fill()
		'On Error GoTo err_
		On Error Resume Next

		If DATAB = False Then
			Call LoadDatabase()
			Exit Sub
		Else
		End If

		cmbUser.Items.Clear()

		Dim users As List(Of ITUser)
		users = userService.GetAllUsers()

		If users.Count = 0 Then
			Dim user As ITUser
			user = userService.AddUser("ADMINISTRATOR", "SWY\X", "ADMINISTRATOR", "Admin")
			users.Add(user)
		End If

		'For Each user As ITUser In users
		'	cmbUser.Items.Add(user.Name)
		'Next

		cmbUser.Bind(users.Select(Function(u) u.Name))

		Dim rs As ADODB.Recordset
		Dim sSQL As String

		rs = New ADODB.Recordset
		rs.Open("UPDATE spr_other SET C='0' WHERE C=''", DB7, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockOptimistic)
		'rs.Close()
		rs = Nothing

		Exit Sub

err_:
		MsgBox(Err.Description)
	End Sub

	Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
		If Len(txtPassword.Text) = 0 Then Exit Sub

		Me.Enabled = False
		Call User_Pro()

		Me.Enabled = True

		'Call User_Pro()
	End Sub

	Private Sub User_Pro()
		Dim objIniFile As New IniFile(PrPath & "base.ini")
		objIniFile.WriteString("general", "DefaultUser", cmbUser.Text)
		objIniFile.WriteString("DB", "DB", unamDB)

		If cmbSUBD.Text <> "MS Access" Then
			objIniFile.WriteString("DB", "SERVER", TextBox1.Text)
			objIniFile.WriteString("DB", "PORT", TextBox2.Text)
			objIniFile.WriteString("DB", "BD", TextBox3.Text)
			objIniFile.WriteString("DB", "USER", TextBox4.Text)
			objIniFile.WriteString("DB", "PASSWORD", TextBox5.Text)
		Else
			Base_Name = cmbBD.Text
			objIniFile.WriteString("general", "file", cmbBD.Text)
		End If

		If DATAB = False Then
			Call LoadDatabase()
		End If

		Dim cfgService As New ConfigureService(ConnectionString)
		Dim cfg As IConfigure
		cfg = cfgService.GetConfigure()

		If IsNothing(cfg) Then
			cfg = cfgService.SaveConfigure("SISADM", "BKO.SHATKI.INFO", "BKO.NET", "Yes", "1.7.2")
		End If

		Dim sVER, tVER As String
		Dim sPass1 As String = ""
		Dim LNGIniFile As New IniFile(sLANGPATH)

		sVER = cfg.access

		tVER = My.Application.Info.Version.Major & "." & My.Application.Info.Version.Minor & "." & My.Application.Info.Version.Build

		If sVER >= "1.7.2" Then

		Else
			MsgBox(LNGIniFile.GetString("frmLogin", "MSG1", "") & vbCrLf & LNGIniFile.GetString("frmLogin", "MSG2", ""), MsgBoxStyle.Information, "BKO.NET - " & tVER)

			End
		End If

		'langini.GetString("messages", "l1", "")

		If Len(txtPassword.Text) = 0 Then Exit Sub

		strPassword = Trim(txtPassword.Text)
		Call EncryptDecrypt(strPassword)
		txtPassword.Text = Temp

		Dim user As ITUser
		user = userService.GetUserByName(cmbUser.Text)

		If IsNothing(user) Then
			MsgBox("This User is not valid", MsgBoxStyle.Critical, "Error!!!")
			Exit Sub
		End If

		If txtPassword.Text = user.Password Then
			uLevel = user.Level
			uSERID = user.User_ID
			UserNames = user.Name

			If Not uLevel = "Admin" Then
				uLevelSetup = user.SETUP
				uLevelTehAdd = user.PCADD
				uLevelTehDel = user.PCDEL
				uLevelNotesAdd = user.CAPADD
				uLevelNotesDel = user.CAPDEL
				uLevelRepAdd = user.REPADD
				uLevelRepDel = user.REPDEL
				uLevelRepEd = user.REPeD
				uLevelPOAdd = user.POADD
				uLevelPODel = user.PODEL
				uLevelCart = user.CARTR
				uLevelPO = user.PO
				uLevelWarehause = user.SCLAD
			End If

			Call SaveActivityToLogDB(LNGIniFile.GetString("frmLogin", "MSG3", ""))

			'Call ALTER_DB()
			Me.Hide()
			frmMain.Show()

			Me.Close()
		Else
			Call SaveActivityToLogDB(LNGIniFile.GetString("frmLogin", "MSG4", ""))

			System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
			Me.Enabled = True
			MsgBox("This Password is not valid", MsgBoxStyle.Critical, "Error!!!")
			txtPassword.Text = ""
			txtPassword.Focus()
			Me.Enabled = True
		End If
		user = Nothing
	End Sub

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		DBserv = TextBox1.Text
		DBtabl = TextBox3.Text
		DBuser = TextBox4.Text
		DBpass = TextBox5.Text
		DBport = TextBox2.Text

		If DATAB = True Then
			UnLoadDatabase()
			Call LoadDatabase()
		Else
			Call LoadDatabase()
		End If

		Call User_fill()
	End Sub

	Private Sub txtPassword_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPassword.KeyDown
		If Len(txtPassword.Text) = 0 Then Exit Sub

		Select Case e.KeyCode
			Case Keys.Enter
				Me.Enabled = False
				Call User_Pro()
		End Select
	End Sub

	Private Sub frmLogin_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		'SendFonts(Me)

		Call LANG_frmLogin()

		Dim objIniFile As New IniFile(PrPath & "base.ini")
		cmbLang.Text = objIniFile.GetString("general", "LANG", "ru.ini")

		Call Find_LANG()

		sLoad = True

		'Me.Height = 230
		'gbData.Top = 54
		'cmbBD.Enabled = True
		'btnLogin.Top = 174
		'btnCancel.Top = btnLogin.Top
		'gbsql.Top = 205

		Call sSUBD()
		userService = New TUserService(ConnectionString)
		logService = New TLogService(ConnectionString)

		Call User_fill()

		Me.Focus()
		txtPassword.Focus()
	End Sub

	Private Sub sSUBD()
		If sLoad = False Then Exit Sub

		Dim langIni As New IniFile(PrPath & "base.ini")
		cmbUser.Text = langIni.GetString("general", "DefaultUser", "")
		cmbSUBD.Text = langIni.GetString("DB", "DB", "")

		If Len(cmbSUBD.Text) = 0 Then cmbSUBD.Text = "MS Access"

		Select Case cmbSUBD.Text
			Case "MS Access"
				gbsql.Visible = False

				Me.Height = Me.Height - gbsql.Height

				'Me.Height = 245
				'gbData.Top = 53
				cmbBD.Enabled = True
				btnDBDir.Enabled = True
				'btnLogin.Top = 194
				'btnCancel.Top = btnLogin.Top
				'gbsql.Top = 225

				unamDB = cmbSUBD.Text

				cmbBD.Text = langIni.GetString("general", "file", "")

				langIni.WriteString("DB", "DB", cmbSUBD.Text)

				Call Find_DB()
			Case Else
				gbsql.Visible = True

				'Me.Height = 408
				'gbData.Top = 214
				'gbsql.Top = 50

				cmbBD.Enabled = False
				btnDBDir.Enabled = False
				'btnLogin.Top = 355
				'btnCancel.Top = btnLogin.Top
				'gbData.Top = 205

				Me.AutoSize = True

				unamDB = cmbSUBD.Text

				TextBox1.Text = langIni.GetString("DB", "SERVER", "")
				TextBox2.Text = langIni.GetString("DB", "PORT", "")
				TextBox3.Text = langIni.GetString("DB", "BD", "")
				TextBox4.Text = langIni.GetString("DB", "USER", "")
				TextBox5.Text = langIni.GetString("DB", "PASSWORD", "")

				DBserv = TextBox1.Text
				DBtabl = TextBox3.Text
				DBuser = TextBox4.Text
				DBpass = TextBox5.Text
				DBport = TextBox2.Text

				langIni.WriteString("DB", "DB", cmbSUBD.Text)
		End Select

		If DATAB = False Then
			Call LoadDatabase()
		Else
			Call UnLoadDatabase()
			Call LoadDatabase()
		End If

		'Call User_fill()
	End Sub

	Private Sub cmbSUBD_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbSUBD.SelectedIndexChanged
		If sLoad = False Then Exit Sub

		Dim objIniFile As New IniFile(PrPath & "base.ini")
		objIniFile.WriteString("DB", "DB", cmbSUBD.Text)

		'Call sSUBD()
	End Sub

	Private Sub cmbBD_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBD.SelectedIndexChanged
		If Len(BasePath) = 0 Then
			BasePath = Directory.GetParent(Application.ExecutablePath).ToString & "\database\"
		End If

		If cmbBD.Text = "" Or Len(cmbBD.Text) = 0 Then Exit Sub

		Base_Name = cmbBD.Text

		If DATAB = True Then
			UnLoadDatabase()
			Call LoadDatabase()
		Else
			Call LoadDatabase()
		End If
		Call User_fill()
	End Sub

	Private Sub btnDBDir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDBDir.Click
		Dim DirectoryBrowser As New FolderBrowserDialog

		' Then use the following code to create the Dialog window
		' Change the .SelectedPath property to the default location
		With DirectoryBrowser
			' Desktop is the root folder in the dialog.

			.RootFolder = Environment.SpecialFolder.Desktop

			If Len(BasePath) = 0 Then
				' Select the C:\Windows directory on entry.
				.SelectedPath = PrPath
			Else
				.SelectedPath = BasePath
			End If

			' Prompt the user with a custom message.
			.Description = "Select the source directory"

			If .ShowDialog = DialogResult.OK Then
				' Display the selected folder if the user clicked on the OK button.
				BasePath = .SelectedPath
			End If
		End With

		Dim objIniFile As New IniFile(PrPath & "base.ini")
		objIniFile.WriteString("general", "BasePath", BasePath & "\")

		BasePath = BasePath & "\"
		Call Find_DB()
	End Sub

	Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
		End
	End Sub

	Private Sub cmbLang_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbLang.SelectedIndexChanged
		Dim objIniFile As New IniFile(PrPath & "base.ini")
		objIniFile.WriteString("general", "LANG", cmbLang.Text)

		sLANGPATH = PrPath & "lang\" & cmbLang.Text

		Call LANG_frmLogin()
	End Sub

	Private Sub txtPassword_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPassword.TextChanged

	End Sub
End Class
